package tech.yunland.shop.web;

import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.domain.service.UserService;
import com.moyuer.bsf.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.model.Reserve;
import tech.yunland.shop.domain.model.ReserveEntry;
import tech.yunland.shop.domain.service.ReserveService;

import javax.validation.Valid;
import java.util.List;

/**
 * 预约控制器
 * 
 * @author: 袁首京<yuanshoujing@gmail.com>
 * 16/4/19
 */
@RestController
@RequestMapping("/reserve")
public class ReserveController extends BaseController {

    @Autowired
    private ReserveService reserveService;

    @Autowired
    private UserService userService;


    /**
     * 读取指定预约
     *
     * @param id 预约标识
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Reserve get(@PathVariable String id) {
        Reserve reserve = reserveService.get(id);
        return reserve;
    }

    /**
     * 保存预约基本信息, 可更改主区域
     *
     * @param reserve 预约信息, json 结构
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void saveOrUpdate(@Valid @RequestBody Reserve reserve) {
        logger.debug("==> save: " + JSON.toJSONString(reserve, true));

        if (reserve.getOrgan() == null) {
            reserve.setOrgan(primaryOrgan);
        }

        if (reserve.getEntries() != null) {
            for (ReserveEntry entry : reserve.getEntries()) {
                entry.setOwner(reserve);
                entry.setFrom(userService.get(entry.getFromId()));
                entry.setTo(userService.get(entry.getToId()));
            }
        }

        reserveService.saveOrUpdate(reserve);

        saveLog("保存预约 [" + reserve.getSn() + "]");
    }

    /**
     * 回复预约
     *
     * @param ownerId      预约标识
     * @param reserveEntry
     */
    @RequestMapping(value = "/{ownerId}", method = RequestMethod.POST)
    public void reply(@PathVariable String ownerId, @Valid @RequestBody ReserveEntry reserveEntry) {
        Reserve reserve = reserveService.get(ownerId);
        if (reserve == null) {
            throw new RuntimeException("未预约");
        }

        reserveEntry.setOwner(reserve);
        reserveEntry.setFrom(userService.get(reserveEntry.getFromId()));
        reserveEntry.setTo(userService.get(reserveEntry.getToId()));

        reserveService.addEntry(reserveEntry);

        saveLog("回复预约 [" + reserve.getSn() + "]");
    }

    /**
     * 删除预约，标记删除（state=-1）
     *
     * @param id 预约标识
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String id) {
        Reserve reserve = reserveService.get(id);
        reserveService.delete(reserve);

        saveLog("删除预约 [" + reserve.getSn() + "]");
    }

    /**
     * 分页查询
     *
     * @param states 状态组
     * @param page   页码
     * @param rows   每页条数
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<Reserve> getResultInfos(
            @RequestParam(required = false) List<Integer> states,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows) {

        Pagination<Reserve> result = new Pagination<Reserve>(page, rows);

        int count = reserveService.getResultSize(states, organIds);
        List<Reserve> records = reserveService.getResultInfos(states, result.getStartIdx(), result.getRows(), organIds);

        result.setCount(count);
        result.setRecords(records);
        return result;
    }
}
